package com.lv.common.untils;


import com.lv.service.UserService;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;


/**
 * Created with IntelliJ IDEA.
 * <p>
 *
 * </p>
 *
 * @Author: 凉薄
 * @Date: 2022/01/08/12:51
 * @Description:
 */
@Component
public class TokenUntil {
    @Autowired
    UserService userService;
    @Autowired
    RedisCache redisCache;
    @Value("${jwt.header}")
    private String header;
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;


    //生成token
    public String createToken(String username){

        Date date = new Date();
        String token = Jwts.builder()
                .setHeaderParam("type", "JWT")
                .setSubject(username)
                .setIssuedAt(date)
                .setExpiration(new Date(date.getTime() + expiration * 1000))
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
        redisCache.setCacheObject("token:"+userService.getByName(username).getId(),token,10, TimeUnit.HOURS);
        return token;
    }
    //解析token
    public Claims parserToken(String jwt){
        try {
            return  Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }
    //jwt是否过期
    public boolean validateToken(Claims claims){
        return claims.getExpiration().before(new Date());
    }

    //通过token解析到用户id
    public Long getIdByToken(HttpServletRequest request){
        String token = request.getHeader(this.header);
        Claims claims = parserToken(token);
        return  userService.getByName(claims.getSubject()).getId();
    }
}
